<template>
  <slot></slot>
  <div class="xtx-infinite-loading" ref="target">
    <div class="loading" v-show="loading">
      <span class="img"></span>
      <span class="text">正在加载...</span>
    </div>
    <div class="none" v-if="finished">
      <span class="img"></span>
      <span class="text">{{finishedText}}</span>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
export default {
  name: 'XtxInfiniteLoading',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    finished: {
      type: Boolean,
      default: false
    },
    finishedText: {
      type: String,
      default: '已经没有了'
    }
  },
  emits: ['load'],
  setup (props, { emit }) {
    // 1. 被观察的对象
  // 2. 不同的API函数
    const target = ref(null)
    // stop 是停止观察是否进入或移出可视区域的行为，这里不需要停止可视区函数
    // target 是观察的目标dom容器，必须是dom容器
    useIntersectionObserver(
      target,
      // isIntersecting 是否进入可视区域，true是进入 false是移出
      // observerElement 被观察的dom
      ([{ isIntersecting }]) => {
      // console.log('可视区开启了', isIntersecting)
      // 根据isIntersecting状态来进行业务逻辑
        if (isIntersecting) {
          if (props.loading === false && props.finished === false) {
            emit('load')
          }
        }
      },
      // 🔔优化： 0 元素刚进入可视区触发，1 表示元素完整进入可视区才触发
      { threshold: [0] }
    )

    return { target }
  }

}
</script>

<style scoped lang='less'>
.xtx-infinite-loading {
  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 50px;
      height: 50px;
      background: url(~@/assets/images/load.gif) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
  .none {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 200px;
      height: 134px;
      background: url(~@/assets/images/none.png) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
}
</style>
